//
//  HTTPRequest.m
//  Worke
//
//  Created by zero on 2018/4/16.
//  Copyright © 2018年 worke. All rights reserved.
//

#import "HTTPRequest.h"
#import "BaseModel.h"
#import "DatasModel.h"
@implementation HTTPRequest




+ (instancetype)shareApiHelper
{
    static HTTPRequest *shareApiHelper;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        
        NSURL *baseUrl = [NSURL URLWithString:BaseUrl];
        shareApiHelper = [[self alloc] initWithBaseURL:baseUrl];
        shareApiHelper.requestSerializer.timeoutInterval = 10.0;
        shareApiHelper.responseSerializer = [AFHTTPResponseSerializer serializer];
        shareApiHelper.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",
                                                                    @"text/json",
                                                                    @"text/javascript",
                                                                    @"text/html",
                                                                    nil];
        
    });
    return shareApiHelper;
}

#pragma mark -->POST请求
/**
 POST请求
 
 @param exhibition <#exhibition description#>
 @param urlString <#urlString description#>
 @param parameters <#parameters description#>
 @param success <#resultObject description#>
 @param errorBlock <#errorBlock description#>
 */
- (void)POSTExhibition:(UIView *)exhibition UrlString:(NSString *)urlString Parameters:(NSDictionary *)parameters Success:(void(^)(id resultObject))success Error:(void(^)(void))errorBlock{
    
    NSString *url = [BaseUrl stringByAppendingString:urlString];
     NSLog(@"\n------------------RequestURL------------------\nURL==%@\n--------parameters-------\n%@\n--------parameters-------\n------------------RequestURL------------------",[self percentPathWithPath:[BaseUrl stringByAppendingString:urlString] params:parameters],parameters);
    
    [ShowMessage showloading:exhibition];
    [self POST:url parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [ShowMessage stopHUD:exhibition];
        NSString *result = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
        BaseModel *model = [BaseModel yy_modelWithJSON:result];
        if (model.code == 200)
            success([DatasModel yy_modelWithJSON:model.datas]);
        else
            [ShowMessage showOnlyString:model.datas[@"error"] showView:exhibition];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [ShowMessage stopHUD:exhibition];
    }];
}
- (void)GETExhibition:(UIView *)exhibition UrlString:(NSString *)urlString Parameters:(NSDictionary *)parameters Success:(void(^)(id resultObject))success Error:(void(^)(void))errorBlock{
    
//    NSString *url = [BaseUrl stringByAppendingString:urlString];
     NSLog(@"\n------------------RequestURL------------------\nURL==%@\n--------parameters-------\n%@\n--------parameters-------\n------------------RequestURL------------------",[self percentPathWithPath: [BaseUrl stringByAppendingString:urlString] params:parameters],parameters);
    [ShowMessage showloading:exhibition];
    [self GET:urlString parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [ShowMessage stopHUD:exhibition];
        NSString *result = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
        BaseModel *model = [BaseModel yy_modelWithJSON:result];
        if (model.code == 200)
            
           success(model.datas);
        else
          [ShowMessage showOnlyString:model.datas[@"error"] showView:exhibition];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [ShowMessage stopHUD:exhibition];
    }];
}

- (void)POSTPitcure:(UIView *)messageView URLString:(NSString *)urlString Parameters:(NSDictionary *)parameters  pitcure:(NSArray *)array Success:(void(^)(id resultObject))succeed error:(void(^)(void))errorBlock
{
  
    NSLog(@"\n------------------RequestURL------------------\nURL==%@\n--------parameters-------\n%@\n--------parameters-------\n------------------RequestURL------------------",[self percentPathWithPath:[@"http://avatar.ytqinyitong.com/web/" stringByAppendingString:urlString] params:parameters],parameters);
    // 基于AFN3.0+ 封装的HTPPSession句柄
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    manager.requestSerializer= [AFHTTPRequestSerializer serializer];
    manager.requestSerializer.timeoutInterval = 20;
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/plain", @"multipart/form-data", @"application/json", @"text/html", @"image/jpeg", @"image/png", @"application/octet-stream", @"text/json", nil];
    [ShowMessage showloading:messageView];
    [manager POST:[@"http://avatar.ytqinyitong.com/web/" stringByAppendingString:urlString]  parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        
      
        for (int i = 0; i < array.count; i++) {
            
            UIImage *image = array[i];
            NSData *imageData = UIImageJPEGRepresentation(image, 0.5);
            NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
            [formatter setDateFormat:@"yyyyMMddHHmmss"];
            NSString *dateString = [formatter stringFromDate:[NSDate date]];
            NSString *fileName = [NSString  stringWithFormat:@"%@.jpg", dateString];
            [formData appendPartWithFileData:imageData name:@"image" fileName:fileName mimeType:@"image/jpg"];
        }
        
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
        NSLog(@"---上传进度--- %@",uploadProgress);
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [ShowMessage stopHUD:messageView];
        NSString *result = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
        BaseModel *model = [BaseModel mj_objectWithKeyValues:result];
        if (model.code == 200)
        succeed(model.datas);
        else{
            [ShowMessage showOnlyString:model.datas[@"error"] showView:messageView];
        }
        
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [ShowMessage stopHUD:messageView];
//        [self showFailMessage:error
//                   targetView:messageView];
        NSLog(@"xxx上传失败xxx %@", error);
        
    }];
}

#pragma mark -->地址字典拼接打印

/**
 地址字典拼接打印
 
 @param path <#path description#>
 @param params <#params description#>
 @return <#return value description#>
 */
- (NSString *)percentPathWithPath:(NSString *)path params:(NSDictionary *)params{
    NSMutableString *percentPath =[NSMutableString stringWithString:path];
    NSArray *keys = params.allKeys;
    NSInteger count = keys.count;
    for (int i = 0; i < count; i++) {
        if (i == 0) {
            [percentPath appendFormat:@"?%@=%@", keys[i], params[keys[i]]];
        }else{
            [percentPath appendFormat:@"&%@=%@", keys[i], params[keys[i]]];
        }
    }
    return [percentPath stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
}


@end
